<?php

namespace app\models\auth_app\doudian;

use app\components\Func;
use app\models\AuthShop;
use Yii;
use app\models\AuthApp;

class AuthAppDoudian extends AuthApp
{
    const APP_ID = '6887526418855757326';
    const APP_SECRET = '2c4a1138-3b40-4216-a0c6-832081c5093f';
    const SERVICE_ID = '4420';
    const MSG_NAMESPACE = 'app\\models\\auth_app\\doudian\\msg\\';

    const URL_CONNECT = 'https://fuwu.jinritemai.com/authorize';
    const URL_TOKEN = 'https://openapi-fxg.jinritemai.com/oauth2/access_token';
    const URL_REFRESH_TOKEN = 'https://openapi-fxg.jinritemai.com/oauth2/refresh_token';

    const URL_API = 'https://openapi-fxg.jinritemai.com';


    //获取消息事件对象
    public function getMsgObj($data){
        if(empty($data)) return ;
        $msg_arr = $data;

        $cname = self::MSG_NAMESPACE.'msg'.$msg_arr['tag'];
        if(!class_exists($cname)){
            $cname = self::MSG_NAMESPACE.'msg0';
        }
        $obj = new $cname();
        $obj->auth_app_id = $this->id;
        $obj->event = $msg_arr['tag'];
        $obj->content = json_encode($data,JSON_UNESCAPED_UNICODE);
        if(!$obj->save()){
            throw new \Exception(json_encode($obj->getErrors(),JSON_UNESCAPED_UNICODE), 1);
        }
        return $obj;

    }
    //刷新token
    public function refreshToken(AuthShop $authShop){
        $arr = [
            'app_id'=>self::APP_ID,
            'app_secret'=>self::APP_SECRET,
            'grant_type'=>'refresh_token',
            'refresh_token'=>$authShop->refresh_token,
        ];
        $response = Func::file_get_contents(self::URL_REFRESH_TOKEN.'?'.http_build_query($arr));
        $data = self::checkResponse($response);
        $authShop->token = $data['access_token'];
        $authShop->token_expire_time = (time() + $data['expires_in']);
        $authShop->refresh_token = $data['refresh_token'];
        if(!$authShop->save()){
            throw new \Exception(json_encode($authShop->getErrors(),JSON_UNESCAPED_UNICODE));
        }
    }
    //获取token
    public function getTokenByCode($code){
        $arr = [
            'app_id'=>self::APP_ID,
            'app_secret'=>self::APP_SECRET,
            'code'=>$code,
            'grant_type'=>'authorization_code',
        ];
        $response = Func::file_get_contents(self::URL_TOKEN.'?'.http_build_query($arr));
        $data = self::checkResponse($response);
        return $data;
    }
    public function initToken($code){
        $token_arr = $this->getTokenByCode($code);
        $authShop = AuthShop::findOne(['auth_app_shop_id'=>$token_arr['shop_id']]);
        if(empty($authShop)){
            $authShop = new AuthShop();
            $authShop->auth_app_id = $this->id;
            $authShop->auth_app_shop_id = $token_arr['shop_id'];
            $authShop->ctime = time();
        }
        $authShop->uid = Yii::$app->user->id;
        $authShop->state = AuthShop::STATE_GOOD;
        $authShop->token = $token_arr['access_token'];
        $authShop->token_expire_time = (time() + $token_arr['expires_in']);
        $authShop->refresh_token = $token_arr['refresh_token'];
        $authShop->refresh_token_expire_time = (time() + 14*86400);
        if(!$authShop->save()){
            throw new \Exception(json_encode($authShop->getErrors(),JSON_UNESCAPED_UNICODE));
        }
        return $authShop;
    }
    //创建授权跳转链接
    public function buildConnectUrl($state=''){
        $arr = [
            'service_id'=> self::SERVICE_ID,
            'state'=> $state,
        ];
        return self::URL_CONNECT.'?'.http_build_query($arr);
    }
    //通用请求方法//自动生成sign，检测请求结果
    protected function getData($arr){
        $arr['app_key'] = self::APP_ID;
        $arr['timestamp'] = date('Y-m-d H:i:s');
        $arr['v'] = 2;
        $arr['sign_method'] = 'md5';
        $arr['sign'] = $this->getSign($arr);
        $response = Func::postData(self::URL_API,$arr);
        $data = self::checkResponse($response);
        return $data;
    }
    /**
     * 	作用：生成签名
     */
    protected function getSign($arr)
    {
        unset($arr['access_token']);
        unset($arr['sign_method']);
        //签名步骤一：按字典序排序参数
        ksort($arr, SORT_STRING);
        ksort($arr['param_json'], SORT_STRING);
        $arr['param_json'] = json_encode($arr['param_json'],JSON_UNESCAPED_UNICODE);
        $str = '';
        foreach ($arr as $key => $val) {
            $str.=$key.$val;
        }
        //签名步骤二：在string前后加入KEY
        $str = self::APP_SECRET.$str.self::APP_SECRET;
        //签名步骤三：MD5加密
        $str = md5($str);
        return $str;
    }
    //检测并格式化抖音返回数据
    static public function checkResponse($response){
        $arr = json_decode($response,1);
        if(empty($arr)) throw new \Exception('抖店接口返回错误',20000);
        if(!isset($arr['error_no'])) throw new \Exception('抖店接口返回错误',20000);
        if($arr['error_no']!=0){
            Yii::error($response);
            throw new \Exception('抖店接口返回错误:'.$arr['error_no'].":".$arr['message'],20000);
        }
        $data = $arr['data'];
        return $data;
    }

}
